# -*- coding: utf-8 -*-

import models.main

import views.main
import helpers.modulemanager

class MainController():

    # @type view views.books.BooksView
    view = None
    model = None

    def __init__(self, frame):
        self.view = views.main.MainView(self, frame)
        self.model = models.main.MainModel()

    def initAction(self):
        pass

    def exitAction(self, event = None):
        self.view.frame.Close()

    def beforeExitAction(self, canVeto):
        if canVeto:
            if self.model.getSyncRequired():
                confirm = self.view.showExitConfirmDialog()
                return not confirm

        return False

    def syncAction(self, event = None):
        moduleMgr = helpers.modulemanager.ModuleManager.getInstance()

        self.view.setStatus(u"Provádím synchronizaci...")
        self.view.showProgressDialog(100)
        self.view.updateProgressDialog(99)
        if self.model.getSyncRequired():
            self.view.setStatus(u"Odesílám změny na server...")            
            if self.model.commit():
                self.view.setStatus(u"Hotovo")
            else:
                self.view.hideProgressDialog()
                self.view.setStatus(u"Při odesílání změn došlo k chybě")
                self.view.showError(u"Při odesílání změn došlo k chybě")
                return

        self.view.setStatus(u"Stahuji data ze serveru...")
        if self.model.update():
            moduleMgr.Get("books").controller.syncAction()
            moduleMgr.Get("notes").controller.syncAction()
        else:
            self.view.setStatus(u"Při synchronizaci došlo k chybě")
            self.view.showError(u"Při synchronizaci došlo k chybě")
        self.view.hideProgressDialog()

    def loginAction(self):
        user = self.view.getUserData()
        if user is not None:
            result = self.model.validateUser(user["login"], user["password"])
            if result is True:
                self.model.setUserName(user["login"]);
                self.syncAction()
            elif result is False:
                self.view.showError(u"Zadané přihlašovací údaje nejsou platné")
                self.loginAction()
            else:
                self.view.showError(result)
                self.loginAction()
        else:
            self.exitAction()

    def aboutAction(self, event):
        self.view.showAboutBox()
